import { Component, OnInit } from '@angular/core';
import { RouterModule } from '@angular/router';
import { Router } from '@angular/router';
import { AppService } from '../../services/app.service';
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { first } from 'rxjs';


@Component({
  selector: 'app-forgot-password-page',
  standalone: true,
  imports: [FormsModule, CommonModule, ReactiveFormsModule, RouterModule],
  templateUrl: './forgot-password-page.component.html',
  styleUrl: './forgot-password-page.component.scss'
})
export class ForgotPasswordPageComponent implements OnInit {

  public forgot_Password_Form: FormGroup;

  constructor(private fb: FormBuilder, private appService: AppService, private route: Router) {
    this.forgot_Password_Form = this.fb.group({
      username: ['', Validators.required],
      phone: ['', Validators.required],
      newpassword: ['', Validators.required],
      confirmPassword: ['', Validators.required],
    });
  }

  async ngOnInit() {

  }

  async resetPassword(forgot_Password_Form: any) {
    console.log(forgot_Password_Form.value.username);
    console.log(forgot_Password_Form.value.phone);
    console.log(forgot_Password_Form.value.newpassword);
    if (forgot_Password_Form.valid) {
      if (forgot_Password_Form.value.newpassword == forgot_Password_Form.value.confirmPassword) {
        await this.appService.resetPassword(
          forgot_Password_Form.value.username,
          forgot_Password_Form.value.phone,
          forgot_Password_Form.value.newpassword).pipe(first()).subscribe(data => {
            console.log(data);
            if (data.message == 'success') {
              this.route.navigate(['/login']);
            }
            if (data.message == 'error') {
              alert("ไม่พบผู้ใช้ หรือ เบอร์โทรศัพท์");

            }
          }, error => {
            alert("ไม่พบผู้ใช้ หรือ เบอร์โทรศัพท์");
          })
      } else {
        alert('รหัสผ่านไม่ตรงกัน');
      }
    }
  }

}
